package test;

import java.awt.BorderLayout;
import java.awt.Component;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import tool.DBUtil;

public class admini extends JFrame {
    private DefaultTableModel tableModel; // 表格数据模型

    /**
     * 构造函数：初始化管理员界面
     */
    public admini() {
        this.setTitle("管理员界面");
        this.setSize(800, 600);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        // 定义表格列名
        String[] columnNames = new String[]{"用户", "密码", "用水量", "用电量", "物业费","物业费状态", "电费状态", "水费状态"};

        // 创建表格模型，并允许所有单元格编辑
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return true;
            }
        };

        // 从数据库加载数据并填充到表格模型
        for (Vector<Object> row : fetchDataFromDB()) {
            tableModel.addRow(row);
        }

        // 创建表格组件并启用自动排序
        JTable table = new JTable(tableModel);
        table.setAutoCreateRowSorter(true);

        // 添加滚动条支持
        JScrollPane scrollPane = new JScrollPane(table);

        // 创建主面板并设置布局
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(scrollPane, BorderLayout.CENTER); // 添加表格区域


        JPanel buttonPanel = new JPanel();

        JButton addButton = new JButton("增加");
        addButton.addActionListener(e -> addRow());

        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(e -> deleteRow());

        JButton searchButton = new JButton("查找");
        searchButton.addActionListener(e -> searchUser(table));

        JButton modifyButton = new JButton("修改");
        modifyButton.addActionListener(e -> modifyRow());

        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> refreshTable());

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(e -> saveDataToDatabase(tableModel));

        buttonPanel.add(addButton);
        buttonPanel.add(modifyButton);
        buttonPanel.add(refreshButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(saveButton);
        buttonPanel.add(searchButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 设置窗口内容面板并显示
        this.add(mainPanel);
        this.setVisible(true);
    }

    private Vector<Vector<Object>> fetchDataFromDB() {
        Vector<Vector<Object>> data = new Vector();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT User, pword, water, elec, wuyefei, WupayState, WaterPayState, ElecPayState FROM 关于用户";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while(rs.next()) {
                Vector<Object> row = new Vector();
                row.add(rs.getString("User"));
                row.add(rs.getString("pword"));
                row.add(rs.getDouble("water"));
                row.add(rs.getDouble("elec"));
                row.add(rs.getDouble("wuyefei"));
                row.add(rs.getString("WupayState")); // 新增物业费状态
                row.add(rs.getString("WaterPayState")); // 新增水费状态
                row.add(rs.getString("ElecPayState")); // 新增电费状态
                data.add(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

        return data;
    }

    private void saveDataToDatabase(DefaultTableModel tableModel) {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DBUtil.getConnection();
            conn.setAutoCommit(true); // 设置为自动提交模式，确保每条SQL立即执行
            String sql = "UPDATE 关于用户 SET pword = ?, water = ?, elec = ?, wuyefei = ?, WupayState = ?, WaterPayState = ?, ElecPayState = ? WHERE User = ?";
            pstmt = conn.prepareStatement(sql);

            for (int i = 0; i < tableModel.getRowCount(); ++i) {
                String username = (String) tableModel.getValueAt(i, 0);
                String password = (String) tableModel.getValueAt(i, 1);
                // 类型检查与转换
                Object wuyefeiObj = tableModel.getValueAt(i, 4);
                String WupayState = (String) tableModel.getValueAt(i, 5);
                String WaterPayState = (String) tableModel.getValueAt(i, 6);
                String ElecPayState = (String) tableModel.getValueAt(i, 7);

                double wuyefei;
                try {
                    wuyefei = wuyefeiObj instanceof Double ? (Double) wuyefeiObj : Double.parseDouble(wuyefeiObj.toString());
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(this, "第 " + (i + 1) + " 行物业费格式错误，请输入数字", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 类型检查与转换
                Object waterObj = tableModel.getValueAt(i, 2);
                Object elecObj = tableModel.getValueAt(i, 3);

                double water;
                try {
                    water = waterObj instanceof Double ? (Double) waterObj : Double.parseDouble(waterObj.toString());
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(this, "第 " + (i + 1) + " 行用水量格式错误，请输入数字", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                double elec;
                try {
                    elec = elecObj instanceof Double ? (Double) elecObj : Double.parseDouble(elecObj.toString());
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(this, "第 " + (i + 1) + " 行用电量格式错误，请输入数字", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                pstmt.setString(1, password);
                pstmt.setDouble(2, water);
                pstmt.setDouble(3, elec);
                pstmt.setDouble(4, wuyefei);
                pstmt.setString(5, WupayState);
                pstmt.setString(6, WaterPayState);
                pstmt.setString(7, ElecPayState);
                pstmt.setString(8, username);


                int rowsAffected = pstmt.executeUpdate();
                if (rowsAffected > 0) {
                    System.out.println("第 " + (i + 1) + " 行已更新");
                } else {
                    System.out.println("第 " + (i + 1) + " 行未更新");
                }
            }

            JOptionPane.showMessageDialog(this, "所有数据已成功保存到数据库", "成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "保存失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DBUtil.closeConnection(conn);

            try {
                if (pstmt != null) {
                    pstmt.close();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void addRow() {
        String username = JOptionPane.showInputDialog(this, "请输入用户名:");
        if (username == null || username.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String password = JOptionPane.showInputDialog(this, "请输入密码:");
        if (password == null || password.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "密码不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        double water = 0.0;
        double electricity = 0.0;

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO 关于用户 (User, pword, water, wuyefei, WupayState, elec, ElecPayState, WaterPayState) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            pstmt.setDouble(3, water);
            pstmt.setString(4, "0"); // 默认物业费状态
            pstmt.setString(5, "0"); // 默认物业费支付状态
            pstmt.setDouble(6, electricity);
            pstmt.setString(7, "0"); // 默认电费支付状态
            pstmt.setString(8, "0"); // 默认水费支付状态
            int rowsAffected = pstmt.executeUpdate();

            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(this, "新用户已成功添加到数据库", "成功", JOptionPane.INFORMATION_MESSAGE);
                refreshTable();
            } else {
                JOptionPane.showMessageDialog(this, "添加用户失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "添加用户失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DBUtil.closeConnection(conn);

            try {
                if (pstmt != null) {
                    pstmt.close();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void modifyRow() {
        String username = JOptionPane.showInputDialog(this, "请输入需要修改的用户名:");
        if (username == null || username.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 检查数据库中是否存在该用户
        if (!isUserExists(username)) {
            JOptionPane.showMessageDialog(this, "用户不存在，请输入正确的用户名", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 提示用户选择要修改的字段
        String[] options = {"密码", "用水量", "用电量" , "物业费", "物业费状态" , "电费状态" , "水费状态"};
        int choice = JOptionPane.showOptionDialog(this, "请选择要修改的字段:", "修改用户信息", 
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

        if (choice == JOptionPane.CLOSED_OPTION) {
            return;
        }

        String newValue = JOptionPane.showInputDialog(this, "请输入新的" + options[choice] + ":");
        if (newValue == null || newValue.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "输入不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 更新数据库
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE 关于用户 SET " + getColumnName(choice) + " = ? WHERE User = ?";
            pstmt = conn.prepareStatement(sql);
            setParameterValue(pstmt, choice, newValue);
            pstmt.setString(2, username);

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(this, "用户信息已成功更新", "成功", JOptionPane.INFORMATION_MESSAGE);
                refreshTable();
            } else {
                JOptionPane.showMessageDialog(this, "更新用户信息失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "更新用户信息失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DBUtil.closeConnection(conn);
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    private boolean isUserExists(String username) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT COUNT(*) FROM 关于用户 WHERE User = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }

    private String getColumnName(int choice) {
        switch (choice) {
            case 0: return "pword";
            case 1: return "water";
            case 2: return "elec";
            case 3: return "wuyefei";
            case 4: return "WupayState";
            case 5: return "WaterPayState";
            case 6: return "ElecPayState";
            default: throw new IllegalArgumentException("无效的选择");
        }
    }

    private void setParameterValue(PreparedStatement pstmt, int choice, String value) throws SQLException {
        switch (choice) {
            case 0:
                pstmt.setString(1, value);
                break;
            case 1:
            case 2:
                try {
                    double numericValue = Double.parseDouble(value);
                    pstmt.setDouble(1, numericValue);
                } catch (NumberFormatException e) {
                    throw new SQLException("请输入有效的数字");
                }
                break;
            case 3: // 物业费
            case 4: // 物业费状态
            case 5: // 水费状态
            case 6: // 电费状态
                pstmt.setString(1, value); // 使用正确的参数索引 1
                break;
            default:
                throw new IllegalArgumentException("无效的选择");
        }
    }

    private void refreshTable() {
        tableModel.setRowCount(0);
        for (Vector<Object> row : fetchDataFromDB()) {
            tableModel.addRow(row);
        }
    }

    private void deleteRow() {
        String username = JOptionPane.showInputDialog(this, "请输入需要删除的用户名:");
        if (username == null || username.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 检查数据库中是否存在该用户
        if (!isUserExists(username)) {
            JOptionPane.showMessageDialog(this, "用户不存在，请输入正确的用户名", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 二次确认删除
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除用户 " + username + " 吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm != JOptionPane.YES_OPTION) {
            return;
        }

        // 删除数据库中的用户数据
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM 关于用户 WHERE User = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(this, "用户已成功删除", "成功", JOptionPane.INFORMATION_MESSAGE);
                refreshTable(); // 刷新表格
            } else {
                JOptionPane.showMessageDialog(this, "删除用户失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "删除用户失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            DBUtil.closeConnection(conn);
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }


    private void searchUser(JTable table) {
        String username = JOptionPane.showInputDialog(this, "请输入要查找的用户名:");
        if (username == null || username.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 遍历表格数据，查找匹配的用户名
        boolean found = false;
        for (int i = 0; i < table.getRowCount(); i++) {
            String currentUsername = (String) table.getValueAt(i, 0); // 获取当前行的用户名
            if (currentUsername.equals(username)) {
                // 高亮显示匹配的行
                table.setRowSelectionInterval(i, i);
                table.scrollRectToVisible(table.getCellRect(i, 0, true));
                found = true;
                break;
            }
        }

        if (!found) {
            JOptionPane.showMessageDialog(this, "未找到用户名为 '" + username + "' 的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new admini());
    }
}